#!usr/bin/env python
# -*-coding: utf-8 -*-
'''
上市公司信息爬虫的工具文件
'''

import os
import sys
import json
import pickle
from collections import Counter
from ConfigParser import ConfigParser

from xtls.logger import get_logger

# ROOT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
# if ROOT_PATH not in sys.path:
#     sys.path.append(ROOT_PATH)

reload(sys)
sys.setdefaultencoding('utf-8')
logger = get_logger(__file__)
config = ConfigParser()


class Stock(object):
    def __init__(self, stock_dict):
        self.id = stock_dict.get('id', None)
        self.stock_code = stock_dict.get('stock_code', None)
        self.stock_name = stock_dict.get('stock_name', None)
        self.stock_market = stock_dict.get('stock_market', None)
        self.lastest_op = stock_dict.get('lastest_op', None)
        self.brief_op = stock_dict.get('brief_op', None)
        self.issue_op = stock_dict.get('issue_op', None)
        self.dividend_op = stock_dict.get('dividend_op', None)
        self.allotment_op = stock_dict.get('allotment_op', None)
        self.management_op = stock_dict.get('management_op', None)
        self.stockstructure_op = stock_dict.get('stockstructure_op', None)
        self.holder_op = stock_dict.get('holder_op', None)
        self.memo_op = stock_dict.get('memo_op', None)


def get_db_config(root_path):
    db_config = {}
    config_path = root_path + '/config.cfg'
    with open(config_path, 'rw') as filecfg:
        config.readfp(filecfg)
    which_db = config.get('using_db', 'db_name')
    db_config['host'] = config.get(which_db, 'host')
    db_config['port'] = config.get(which_db, 'port')
    db_config['user'] = config.get(which_db, 'username')
    db_config['pw'] = config.get(which_db, 'password')
    db_config['db'] = config.get(which_db, 'db')
    return db_config


def get_default_tab_op_for_A():
    DEFAULT_TAB_OP_FOR_A = {
        'lastest_op': 'UPDATE',
        'brief_op': 'UPDATE',
        'issue_op': 'UPDATE',
        'dividend_op': 'UPDATE',
        'allotment_op': 'UPDATE',
        'management_op': 'UPDATE',
        'stockstructure_op': 'INSERT',
        'holder_op': 'INSERT',
        'memo_op': 'INSERT',
    }
    return DEFAULT_TAB_OP_FOR_A


def get_default_tab_op_for_xsb():
    DEFAULT_TAB_OP_FOR_XSB = {
        'lastest_op': 'NOTHING',
        'brief_op': 'UPDATE',
        'issue_op': 'NOTHING',
        'dividend_op': 'NOTHING',
        'allotment_op': 'NOTHING',
        'management_op': 'UPDATE',
        'stockstructure_op': 'NOTHING',
        'holder_op': 'INSERT',
        'memo_op': 'NOTHING',
    }
    return DEFAULT_TAB_OP_FOR_XSB


def get_stock_table_field():
    stock_table_field = ['id', 'stock_code', 'stock_name', 'stock_market',
                         'lastest_op', 'brief_op', 'issue_op', 'dividend_op', 'allotment_op', 'management_op',
                         'stockstructure_op', 'holder_op', 'memo_op', 'alive_op', 'active_op']
    return stock_table_field


def camel_to_underline(camel_format):
    '''
        驼峰命名格式转下划线命名格式
    '''
    underline_format = ''
    if isinstance(camel_format, str):
        for _s_ in camel_format:
            underline_format += _s_ if _s_.islower() else '_'+_s_.lower()
    if underline_format.startswith('_'):
        underline_format = underline_format[1:]

    return underline_format


class InsertError(Exception):
    pass


# ------------------------------get_province_目前没有用这个方法获取省份信息-----------------------------
CURRENT_PATH = os.path.dirname(__file__)
if CURRENT_PATH:
    CURRENT_PATH = CURRENT_PATH + "/"

def find_province_city(text):
    filename = 'resident_revised.pkl'
    pickleFile = file(CURRENT_PATH + filename,'r')
    mapping = pickle.load(pickleFile)
    pickleFile.close()
    province_dic = dict()
    city_dic = dict()
    for item in mapping['mapprovince'].keys():
        if text.find(item)!=-1:
            if mapping['mapprovince'][item] in province_dic.keys():
                province_dic[mapping['mapprovince'][item]] += 1
            else:
                province_dic[mapping['mapprovince'][item]] = 1
    provinceName = Counter(province_dic).most_common()[0][0]
    for item in mapping['mapcity'].keys():
        if text.find(item)!=-1:
            if mapping['mapcity'][item] in city_dic.keys():
                city_dic[mapping['mapcity'][item]] += 1
            else:
                city_dic[mapping['mapcity'][item]] = 1
    if len(city_dic)>=1:
        cityName = Counter(city_dic).most_common()[0][0]
    else:
        cityName = None
    return provinceName, cityName

# ---------------------------------------------------------------------

if __name__ == '__main__':
    province, city = find_province_city(u'广昌县广昌工业园区')
    print province
    print city
